package com.uinnova.product.eam.init;

import com.uinnova.project.base.diagram.util.RedisUtil;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.UserInfo;
import com.uino.util.sys.CurrentUserGetter;
import lombok.extern.slf4j.Slf4j;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Description 自定义获取当前用户方法
 * @Author wang
 * @Date 2021-08-27-17:27
 * @version 1.0
 */
@Component
@Slf4j
@ConditionalOnProperty(prefix = "monet.login",name = "loginMethod",havingValue = "xinwang")
public class XinwangSSOCurrentUser implements CurrentUserGetter {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IUserApiSvc userSvc;

    /**
     * @Author wang
     * @Description 获取当前用户的登录信息
     * @Date 17:30 2021/8/27
     * @Param []
     *
     * @return*/
    @Override
    public SysUser getCurrentUserInfo() {
        //已校验的用户无需再次校验
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attrs != null;
        HttpServletRequest request;
        try {
            request = attrs.getRequest();
            // 获取用户的账号、这里是AD域账号来自employeenum字段，
            String username = request.getRemoteUser();
            // 获取用户完整信息
            AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
            /*
             isFromNewLogin=false,
             lastPwdChange = 2021-05-06 10:58:53,
             employeenum=lichuanbei,
             authenticationDate=2021-05-26T22:31:43.051+08:00[PRC],
             roles=,
             successfulAuthenticationHandlers=cimsAuthenticationHandler,
             userid=1b8fbeb0a819cda7e3071b3579136deb,
             realname=李川北,
             credentialType=CimsCredential,
             authWay=8,
             phone=15282896629,
             authenticationMethod=cimsAuthenticationHandler,
             permissions=,
             activation_mode=3,
             longTermAuthenticationRequestTokenUsed=false,
             email=lichuanbei@hopebank.com,
             account=,
             otherInfos={"userid":"1b8fbeb0a819cda7e3071b3579136deb","dataSourceId":26,"createTime":"2019-12-12","updateTime":"2021-04-21","email":"lichuanbei@hopebank.com","employeeStatus":1,"employeenum":"lichuanbei","phone":"15282896629","realname":"李川北
             */
            final Map attributes = principal.getAttributes();
            return convertToEaUser(attributes);
        } catch (NullPointerException exception) {
            return null;
        }
    }

    private SysUser convertToEaUser(Map attributes) {
        if (log.isDebugEnabled()) log.debug("新网用户数据：{}", attributes);

        SysUser sysUser = new SysUser();
        Object userid = attributes.get("employeenum");
        if (userid != null) {
            UserInfo userInfo = userSvc.getUserInfoByLoginCode(userid.toString());
            if (userInfo == null) {
                throw new RuntimeException("用户不存在，请联系管理员");
            }
            if (log.isDebugEnabled()) log.debug("获取ea用户：{}", userInfo);
            return userInfo;
        }
        return sysUser;
    }

    @Override
    public SysUser getCurrentUserInfo(String token) {
        return getCurrentUserInfo();
    }

    @Override
    public String getCurrentToken() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attrs.getRequest();
        return request.getRemoteUser(); // 获取用户的账号、这里是AD域账号来自employeenum字段，
    }
}


